package com.bsy.framework.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter

/**
 * @创建者 Sincerity
 * @创建时间 2023/3/5 15:32
 * @类描述 FragmentStateAdapter
 */
class ViewPage2FragmentAdapter(
    fragmentManager: FragmentManager, lifecycle: Lifecycle, private var fragments: MutableList<Fragment>
) : FragmentStateAdapter(fragmentManager, lifecycle) {
    /**class ViewPage2FragmentAdapter(activity: FragmentActivity, var fragments: SparseArray<Fragment>) :
    FragmentStateAdapter(activity) {*/
    //FragmentStateAdapter内部自己会管理已实例化的fragment对象，所以不需要考虑复用的问题。
    override fun createFragment(i: Int): Fragment {
        return fragments[i]
    }

    override fun getItemCount(): Int {
        return fragments.size
    }

    fun setData(fragments: MutableList<Fragment>) {
        this.fragments = fragments
    }

    override fun getItemId(position: Int): Long {
        // 返回唯一标识符，使用Fragment的哈希码以确保唯一性
        return fragments[position].hashCode().toLong()
    }

    override fun containsItem(itemId: Long): Boolean {
        // 判断是否包含给定的标识符
        return fragments.any { it.hashCode().toLong() == itemId }
    }
}
